package com.miaosha.fx.jsjava;

import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;

import javafx.scene.web.WebEngine;
import netscape.javascript.JSObject;

import org.apache.commons.lang.time.DateUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.miaosha.MediaService;
import com.utils.DateUtil;

/**
 * js调用java
 * 注意事项：千万不能重载方法，否则js不能识别
 * @author TANGJZ2
 *
 */
public class Js2Java {
	
    private WebEngine webEngine;
	public static Logger logger = Logger.getLogger(Js2Java.class);
	private AtomicBoolean atomicBoolean = new AtomicBoolean(false);
	private String couponId = null;
	
	public Js2Java(WebEngine webEngine) {
		super();
		this.webEngine = webEngine;
		Java2Js.win = (JSObject) this.webEngine.executeScript("window");
	}

	/**
	 * 开始执行秒杀程序
	 * @param username 账户
	 * @param password 密码
	 * @param time 开始时间
	 */
	public void startJob(String username, String password, String time){
		if(atomicBoolean.get()){
			Java2Js.pushMessage("任务正在执行中，请先点击结束......");
			return;
		}
		atomicBoolean.set(true);
		try {
			Date startTime = DateUtil.parse(DateUtil.format(new Date(), "yyyy-MM-dd") + " " + time, "yyyy-MM-dd HH:mm:ss.S");
			logger.info("输入的时间格式："+time);
			if(startTime == null){
				Java2Js.pushMessage("请输入正确的时间格式......");
				return;
			}
			MediaService.login(username, password);
			Java2Js.pushMessage("登录成功......");
			String[] couponIds = null;
			if(couponId == null){
				couponIds = MediaService.getCouponIds();
			}else{
				couponIds = new String[]{couponId};
			}
			Java2Js.pushMessage("获取优惠券ID：" + JSON.toJSONString(couponIds));
			for (int i = 0; i < couponIds.length; i++) {
				HttpGet httpGet = new HttpGet(MediaService.MIAOSHA_URL + couponIds[i]);
				MediaService.createSchedule(DateUtils.addHours(startTime, 2*i), httpGet);
				Java2Js.pushMessage("创建秒杀任务成功，券ID：" + couponIds[i]);
			}
			
		}catch (Exception e) {
			atomicBoolean.set(false);
			Java2Js.pushMessage(e.getMessage());
			logger.error(e);
		}
	}
	
	/**
	 * 开始执行秒杀程序
	 * @param username 账户
	 * @param password 密码
	 * @param time 开始时间
	 * @param couponId 券Id
	 */
	public void start(String username, String password, String time, String couponId){
		this.couponId = couponId;
		startJob(username, password, time);
	}
	
	public void stop(){
		MediaService.stop();
		Java2Js.pushMessage("秒杀程序已停止......");
		atomicBoolean.set(false);
	}
	
	public String pullMessage(){
		String str = Java2Js.popMessage();
		return str;
	}
}
